package com.ruoyi.common.core.page;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.R;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 表格分页数据对象
 * 
 * @author ruoyi
 */
@Data
@Accessors(chain = true)
@ApiModel(value = "TableDataInfo", description = "表格分页数据对象")
public class TableDataInfo<T> implements Serializable
{
    private static final long serialVersionUID = 1L;

    /** 总记录数 */
    @ApiModelProperty(value = "总记录数", example = "1")
    private long total;

    /** 列表数据 */
    @ApiModelProperty(value = "列表数据")
    private List<T> rows;

    /** 消息状态码 */
    @ApiModelProperty(value = "消息状态码")
    private int code;

    /** 消息内容 */
    @ApiModelProperty(value = "消息内容")
    private String msg;

    /**
     * 表格数据对象
     */
    public TableDataInfo()
    {
    }

    /**
     * 分页
     * 
     * @param list 列表数据
     * @param total 总记录数
     */
    public TableDataInfo(List<T> list, int total)
    {
        this.rows = list;
        this.total = total;
    }

    public static <T> TableDataInfo<T> success() {
        return success(Collections.emptyList(), 0);
    }

    public static <T> TableDataInfo<T> success(List<T> list, long total)
    {
        return restResult(list, total, R.SUCCESS, "查询成功");
    }

    public static <T> TableDataInfo<T> fail()
    {
        return restResult(null, R.FAIL, null);
    }

    public static <T> TableDataInfo<T> fail(String msg)
    {
        return restResult(null, R.FAIL, msg);
    }

    private static <T> TableDataInfo<T> restResult(List<T> list, int code, String msg)
    {
        long total = 0L;
        if (Objects.nonNull(list)) {
            total = new PageInfo<>(list).getTotal();
        }
        return restResult(list, total, code, msg);
    }

    private static <T> TableDataInfo<T> restResult(List<T> list, long total, int code, String msg)
    {
        TableDataInfo<T> rspData = new TableDataInfo<>();
        rspData.setCode(code);
        rspData.setRows(list);
        rspData.setMsg(msg);
        rspData.setTotal(total);
        return rspData;
    }

    public static <T> Boolean isError(TableDataInfo<T> ret)
    {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(TableDataInfo<T> ret)
    {
        return R.SUCCESS == ret.getCode();
    }
}
